package com._520it.wms.realm;

import com._520it.wms.domain.Employee;
import com._520it.wms.domain.Role;
import com._520it.wms.service.IEmployeeService;
import com._520it.wms.service.IPermissionService;
import com._520it.wms.service.IRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    IPermissionService permissionService;

    @Override
    public String getName() {
        return "MyRealm";
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Employee currentUser = (Employee) principalCollection.getPrimaryPrincipal();
        //模拟查找数据库的权限
        //判断是否是超级管理员
        List<String> roles = new ArrayList<>();
        List<String> permissions = new ArrayList<>();
        if (currentUser.getAdmin()) {//判断是否是超级管理员
            List<Role> roleList = roleService.listAll();
            for (Role role : roleList) {
                roles.add(role.getSn());
            }
            permissions = Arrays.asList("*:*");

        } else {
            //根据用户的id查询角色信息
            roles = roleService.queryByEmpId(currentUser.getId());
            permissions = permissionService.queryByEmpId(currentUser.getId());

        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);
        return info;


    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        //根据用户名查询用户信息
        Employee employee = employeeService.queryByName(username);
        //模拟数据库操作
        if (employee == null) {
            return null;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee, employee.getPassword(), getName());
        return info;
    }

    //清空缓存
    public void clearCache() {
        //获取do用户身份信息
        super.clearCache(SecurityUtils.getSubject().getPrincipals());
    }
}
